package com.history.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.history.business.ArticleManager;

public class SpringContextFactory {
	private static Logit m_log = Logit.getInstance(SpringContextFactory.class);

	// Application Context
	public static ApplicationContext context 		= null;
	public static ApplicationContext contextLocal 	= null;
	
	// Manager
	private static ArticleManager 	articleManager 	= null;
	private static ArticleManager 	articleManagerLocal 	= null;

	private static final String SPRING_ALL_CONFIG_FILE 			= "spring-all-config.xml";
	private static final String SPRING_ALL_CONFIG_FILE_LOCAL 	= "spring-local-all-config.xml";
	
	// Server
	private static final String SPRING_ARTICLE_MANAGER_BEAN = "ArticleManager";
	
	// Local
	private static final String SPRING_ARTICLE_MANAGER_LOCAL_BEAN = "ArticleManagerLocal";

	//AccountManager
	public static ArticleManager getArticleManager(boolean isServer) {
		try {
			if (isServer) {
				if (articleManager == null) {
					if (getApplicationContext() != null) {
						articleManager = (ArticleManager) getApplicationContext().getBean(SPRING_ARTICLE_MANAGER_BEAN);
					}
				}
				return articleManager;
			} else {
				if (articleManagerLocal == null) {
					if (getApplicationContextLocal() != null) {
						articleManagerLocal = (ArticleManager) getApplicationContextLocal().getBean(SPRING_ARTICLE_MANAGER_LOCAL_BEAN);
					}
				}
				return articleManagerLocal;
			}
		} catch (Exception e) {
			m_log.error(e.getMessage(), e);
		}
		return null;
	}

	public synchronized static ApplicationContext getApplicationContext() {
		try {
			if (context == null) {
				context = new FileSystemXmlApplicationContext(
						Helpers.getFullPath(SPRING_ALL_CONFIG_FILE));
			}
		} catch (Exception e) {
			m_log.error(e.getMessage(), e);
		}
		return context;
	}

	public synchronized static ApplicationContext getApplicationContextLocal() {
		try {
			if (contextLocal == null) {
				contextLocal = new FileSystemXmlApplicationContext(
						Helpers.getFullPath(SPRING_ALL_CONFIG_FILE_LOCAL));
			}
		} catch (Exception e) {
			m_log.error(e.getMessage(), e);
		}
		return contextLocal;
	}
}